package com.webcamtracker.color.segmentation;

import com.webcamtracker.image.color.ColorSampleFactory;
import com.webcamtracker.image.color.hsv.HSVColor;
import com.webcamtracker.image.color.rgb.ColorSampler;

import java.awt.image.BufferedImage;

public class HSVColorPlannerPreProcessor
        implements PreProcessor {
    private static final int HUE_RANGES = 16;
    private static final int SATURATION_RANGES = 2;
    private static final int BRIGHTNESS_RANGES = 2;


    public BufferedImage process(BufferedImage image) {

        final ColorSampler colorSampler = ColorSampleFactory.getSampler("HSV");
        final int width = image.getWidth();
        final int height = image.getHeight();


        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                final HSVColor hsvColor = (HSVColor) colorSampler.getColorAt(image, x, y);
                final float hue = calculate(hsvColor.getHue(), HUE_RANGES);
                final float saturation = calculate(hsvColor.getSaturation(), SATURATION_RANGES);
                final float brightness;
                if (hsvColor.getBrightness() > 0.2) {
                    brightness = calculate(hsvColor.getBrightness(), BRIGHTNESS_RANGES);
                }else{
                    brightness = 0;
                }
                image.setRGB(x, y, java.awt.Color.HSBtoRGB(hue, saturation, brightness));
            }
        }
        return image;
    }

    private static float calculate(double value, int ranges) {
        return (float) (Math.ceil(value * (ranges)) * 1 / ranges);
    }
}
